<template>
  <div class="create-post-page">
    <h4 class="margin-start">{{isEditMode ? '编辑文章' : '新建文章'}}</h4>
    <Uploader
      :action="'http://apis.imooc.com/api/upload'"
      @fileUploaded="handleFileUploaded"
      :beforeUpData="beforeUpData"
      :uploaded="uploadedImageData"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="spinner-border" role="status">
          <span class="visually-hidden">Loading...</span>
        </div>
        <h2 class="text-primary">正在加载中...</h2>
      </template>
      <template #success="dataProps">
        <img :src="dataProps.uploadedData" alt="jpg">
      </template>
      <template #error>
        <h2 class="text-primary">上传出错</h2>
      </template>
    </Uploader>
    <validate-form @form-submit="submitFn">
      <div class="mb-3">
        <label class="form-label">文章标题</label>
        <validate-input :rule="tliteRules" v-model="val.tliteValue" type="text" placeholder="请输入文章标题"></validate-input>
      </div>
      <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">文章详情</label>
        <validate-input :rule="textRules" v-model="val.textValue" tag="textarea" rows="10" placeholder="请输入文章详情"></validate-input>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { ref, defineComponent, onMounted, reactive } from 'vue'
import ValidateForm from './ValidateForm.vue'
import ValidateInput from './ValidateInput.vue'
import { useStore } from 'vuex'
import { beforeUploadCheck } from '../helps'
import { GlobalDataProps, PostProps, loaderResType, imageData } from '../store'
import createMessage from './createMessage'
import { useRouter, useRoute } from 'vue-router'
import Uploader from './Uploader.vue'
interface textsRules{
  type: 'required';
  message: string;
}

export default defineComponent({
  name: 'CreatePost',
  components: {
    ValidateForm,
    ValidateInput,
    Uploader
  },
  setup () {
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const store = useStore<GlobalDataProps>()
    const uploadedImageData = ref()
    const tliteRules: textsRules[] = [
      {
        type: 'required',
        message: '文章标题不能为空'
      }
    ]
    const textRules: textsRules[] = [
      {
        type: 'required',
        message: '文章详情不能为空'
      }
    ]
    const val = reactive({
      tliteValue: '',
      textValue: ''
    })
    onMounted(() => {
      if (isEditMode) {
        store.dispatch('postDetailRst', route.query.id).then((res: PostProps) => {
          if (res.image) {
            uploadedImageData.value = { data: res.image }
          }
          val.tliteValue = res.title
          val.textValue = res.content || ''
        })
      }
    })
    let imageId = ''
    const handleFileUploaded = (rawData: loaderResType<imageData>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }
    const submitFn = (value: boolean) => {
      if (value) {
        const { column, _id } = store.state.user
        if (column) {
          const PostData: PostProps = { // 文本数据
            column: `${column}`,
            title: val.tliteValue,
            content: val.textValue,
            author: `${_id}`
          }
          if (imageId) {
            PostData.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'postDetailRst'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: PostData
          } : PostData
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功, 2秒后跳转到文章', 'success', 2000)
            setTimeout(() => {
              router.push({ name: 'columnDetail', params: { id: column } })
            }, 2000)
          })
        }
      }
    }
    // 上传文件类型限制功能
    const beforeUpData = (file: File) => {
      const format = ['image/jpeg', 'image/png']
      const result = beforeUploadCheck(file, { format, size: 1 })
      if (result.passed) {
        createMessage('上传成功', 'success')
      } else {
        if (result.error === 'format') {
          createMessage('上传图片只能是image/jpeg格式', 'error')
        } else {
          createMessage('上传图片大小超出1M', 'error')
        }
      }

      return result.passed
    }
    //  成功结果触发
    const onfileUploaded = (resData: loaderResType<imageData>) => {
      createMessage(`上传成功，成功id为：${resData.data._id}`, 'success')
    }

    return { tliteRules, textRules, val, submitFn, onfileUploaded, beforeUpData, handleFileUploaded, uploadedImageData, isEditMode }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height:200px;
  cursor: pointer;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
